package com.blb.community.Config;

import com.blb.community.Utils.JwtUtils;
import com.blb.community.Utils.RsaUtils;
import com.blb.community.service.ZyOwnerService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {

    private ZyOwnerService userService=ApplicationContextConfig.getApplicationContext().getBean(ZyOwnerService.class);


    public static final String ACCESS_TOKEN_HEADER="tokens";

    public TokenAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader(ACCESS_TOKEN_HEADER);
        if(token==null){
            throw new RuntimeException("无用户");
        }
        try{
            String username = JwtUtils.getUsernameFromToken(token, RsaUtils.publicKey);
            UsernamePasswordAuthenticationToken uToken=new UsernamePasswordAuthenticationToken(username,"",new ArrayList<GrantedAuthority>());
            SecurityContextHolder.getContext().setAuthentication(uToken);
        }catch (Exception ex){
             log.error(ex.getMessage());
        }
        chain.doFilter(request, response);
//        //获得请求头中的token
//        String allToken = request.getHeader(ACCESS_TOKEN_HEADER);
//        String accessToken=allToken.substring(allToken.indexOf(":")+2,allToken.indexOf(",")-1);
//        if(accessToken == null){
//            throw new RuntimeException("accessToken为空");
//        }
//        String username = null;
//        try {
//            //解析请求头
//            username = JwtUtils.getUsernameFromToken(accessToken, RsaUtils.publicKey);
//            //解析成功就创建令牌，交给security，让请求通信
//            UsernamePasswordAuthenticationToken uToken = new UsernamePasswordAuthenticationToken(username,"",null);
//            SecurityContextHolder.getContext().setAuthentication(uToken);
////            if(true){
////                throw  new ExpiredJwtException(null,null,null);
////            }
//        }catch (ExpiredJwtException ex){
//            log.info("access-token过期开始刷新..");
////            String refreshToken = request.getHeader(REFRESH_TOKEN_HEADER);
//            String refreshToken=allToken.substring(allToken.lastIndexOf(":")+2,allToken.length()-2);
//            try {
//                //access-token过期后，去解析refresh-token
//                String s = JwtUtils.getUsernameFromToken(refreshToken, RsaUtils.publicKey);
//                log.info("refresh-token解析成功",s);
//                //如果能解析成功，就重新生成access-token和refresh-token
//                accessToken = JwtUtils.generateToken(username, RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES);
//                String uid = accessToken.substring(0,10);
//                refreshToken = JwtUtils.generateToken(uid, RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES * 2);
//                //发送给客户端，客户端重新保存
//                HashMap<String,String> tokens = new HashMap<>();
//                tokens.put("accessToken",accessToken);
//                tokens.put("refreshToken",refreshToken);
//                //让自定义响应头可见
//                response.setHeader("Access-Control-Expose-Headers","tokens");
//                //把两个token放到响应头和响应数据一起返回
//                response.setHeader("tokens",new ObjectMapper().writeValueAsString(tokens));
//            }catch (ExpiredJwtException ex1){
//                log.error("refresh-token过期",ex1);
//            }
//        }catch (Exception ex){
//            log.error("解析token失败",ex);
//        }
//        //执行下一个过滤器
//        chain.doFilter(request,response);
    }
}
